import { CallHandler, Injectable, NestInterceptor, ExecutionContext, Inject } from '@nestjs/common'
import { map, Observable } from 'rxjs'
import { WINSTON_MODULE_PROVIDER } from 'nest-winston'
import { Logger } from 'winston'
import { Request } from 'express'

interface Data<T> {
  data: T
  status: number
  message: string
  success: boolean
}

@Injectable()
export class TransformResponseInterceptor<T> implements NestInterceptor {
  constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<Data<T>> {
    const ctx = context.switchToHttp()
    const request = ctx.getRequest<Request>()

    return next.handle().pipe(
      map((response) => {
        const res = context.switchToHttp().getResponse()
        if (res.get('Content-Type')?.includes('image/')) return response
        const { data, message, status } = response

        const responseData = {
          data: data ?? response,
          status: status || 200,
          message: message || '请求成功',
          success: true
        }

        // 记录日志
        const { method, originalUrl, body, query, params, ip } = request
        this.logger.info('response', {
          req: { method, url: originalUrl, body, query, params, ip }
          // res: responseData
        })
        return responseData
      })
    )
  }
}
